package com.fanshe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo4 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<?> c = Class.forName("com.fanshe.Student");
        // 返回所有公共的成员变量
        Field[] commonFields = c.getFields();
        for (Field field : commonFields) {
            System.out.println(field);
        }

        System.out.println("==================");
        // 返回所有的成员变量
        Field[] declaredFields = c.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }

        System.out.println("==================");
        // 返回单个公共的成员变量
        Field addressField = c.getField("address");
        // 获取无参构造方法创建对象
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();
        // Field提供有关类或接口的单个字段的信息和动态访问
        // void set(Object obj, Object value) 将指定的对象参数中由此Field对象表示的字段设置为指定的新值
        addressField.set(obj, "西安"); // 给obj对象的成员变量addressField赋值为西安
        System.out.println(obj);

        System.out.println("==================");
        // 返回单个成员变量
        Field name = c.getDeclaredField("name");
        System.out.println(name);
    }
}
